//
//  TTExistGoodsChooseView.m
//  TaoTuo
//
//  Created by apple on 2020/11/26.
//  Copyright © 2020 刘广. All rights reserved.
//

#import "TTExistGoodsChooseView.h"
#import "TTExistGoodsTableViewCell.h"
#import "TTDetailStockListModel.h"
#import "TTXianhuoModel.h"
#import <UIView+TYAlertView.h>
#import "TTExistGoodsChooseHeaderView.h"
#import "TTCustomConditionModel.h"
#import "LLScreenView.h"
#import "TTNewOrderDetailViewController.h"

@interface TTExistGoodsChooseView ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *selectArray;

@property (nonatomic, strong) TTXianhuoModel *existModel;

@property (nonatomic, strong) TTExistGoodsChooseHeaderView *headerView;
/// 原数组
@property (nonatomic, strong) NSMutableArray *originalArray;

@end

@implementation TTExistGoodsChooseView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self setupSubviews];
        
        @weakify(self)
        self.headerView.filterConditionChangedBlock = ^(NSString * _Nonnull filterString) {
            @strongify(self)
            if (filterString.length == 0) {
                self.dataArray = self.originalArray;
            } else {
                NSPredicate *predicate = [NSPredicate predicateWithFormat:filterString];
                self.dataArray = [self.originalArray filteredArrayUsingPredicate:predicate].mutableCopy;
                
            }
            [self.tableView reloadData];
        };
        
    }
    return self;
}

- (void)showInView:(UIView *)view
{
    if (view) {
        [LLAnimationAlertView animationAlertViewWithView:self animationType:AnimationFromBottom tapBgDismiss:YES inView:view];
    } else {
        [LLAnimationAlertView animationAlertViewWithView:self animationType:AnimationFromBottom];
    }
}

- (void)dismiss
{
    [LLAnimationAlertView dismissView:self];

}

- (void)setStyleLibraryId:(NSString *)styleLibraryId
{
    _styleLibraryId = styleLibraryId;
    
    [self getExistGoodsListDatas];
}

// 查询现货数据
- (void)getExistGoodsListDatas
{
    NSString *isOldUser = [TTLoginSingle sharedSingle].userModel.IsOldUser ? @"true" : @"false";
    
    NSDictionary *dic = @{
        @"param.styleLibraryId" : self.styleLibraryId,
        @"param.finishedProduct" : @(0),
        @"param.isOldUser" : isOldUser
    };
//    NSMutableDictionary *mDic = dic.mutableCopy;
//    if (self.otherParams) {
//        [mDic addEntriesFromDictionary:self.otherParams];
//    }
//    //如果是显示所有数据使用dic
//    NSDictionary *parmasDic = self.lookAllGuigeData ? dic : mDic;
    NSDictionary *parmasDic = dic;
    
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getXianhuo_api parameters:parmasDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        
        self.existModel = [TTXianhuoModel modelWithJSON:responseObject];
        
        [self.dataArray addObjectsFromArray:self.existModel.StockList];
        self.originalArray = self.dataArray.mutableCopy;
        self.headerView.model = self.existModel;
        
        [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.headerView.mas_bottom);
        }];
        
        [self setupFooterView];
        [self.tableView reloadData];
        
        int priceMin = 0;
        int priceMax = 0;
        for (int i = 0; i < self.dataArray.count; i++) {
            TTDetailStockListModel *listModel = self.dataArray[i];
            if (i == 0) {
                priceMin = listModel.Price.intValue;
                priceMax = listModel.Price.intValue;
            } else {
                if (listModel.Price.intValue > priceMax) {
                    priceMax = listModel.Price.intValue;
                }
                if (listModel.Price.intValue < priceMin) {
                    priceMin = listModel.Price.intValue;
                }
            }
        }
        
        TTCustomConditionModel *customModel = [TTCustomConditionModel new];
        customModel.PriceMin = [NSString stringWithFormat:@"%d", priceMin];
        customModel.PriceMax = [NSString stringWithFormat:@"%d", priceMax];
        customModel.CycleMin = self.existModel.CycleMin;
        customModel.CycleMax = self.existModel.CycleMax;
        customModel.CoverMapImg = self.CoverMapImg;
        
        self.headerView.customModel = customModel;
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        
    } showLoadingInView:nil];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTDetailStockListModel *model = self.dataArray[indexPath.row];
    TTExistGoodsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.model = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTDetailStockListModel *model = self.dataArray[indexPath.row];
    model.selected = !model.selected;
    if (model.selected) {
        if (![self.selectArray containsObject:model]) {
            [self.selectArray addObject:model];
        }
    } else {
        [self.selectArray removeObject:model];
    }
    
    [self.tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationFade];
    
}

/// 去定制
- (void)gotoCustomView
{
    LLScreenView *customView = [[LLScreenView alloc] initWithFrame:CGRectMake(0, 0, self.width, SCREEN_HEIGHT*0.9)];
    customView.CoverMapImg = self.CoverMapImg;
    customView.styleLibraryId = self.styleLibraryId;
    [customView showInView:self.viewController.view];
}

/// 加入购物车
- (void)addCartBtnClick
{
    if (self.selectArray.count == 0) {
        [MBProgressHUD showAutoHideMessage:@"请选择货品"];
        return;
    }
    
    NSMutableArray *goodsArray = [NSMutableArray array];
    for (TTDetailStockListModel *listModel in self.selectArray) {
        listModel.selected = YES;
        NSDictionary *dic = @{
            @"GoodsType": @(listModel.StockType),
            @"GoodsTitle": self.detailModel.GoodsTitle,
            @"GoodsImage": self.detailModel.CoverMapImg,
            @"GoodsBarCode": listModel.GoodsBarCode,
            @"AddPrice": listModel.Price,
            @"StyleLibraryId": self.styleLibraryId,
            @"CategoryName": self.detailModel.CategoryName,
            @"InsertSize": listModel.InsertSize1,
            @"Number": @(listModel.buyCount == 0 ? 1 : listModel.buyCount),
            @"CustomizedGoldColor" : listModel.GoldColor,
            @"BuyNumberMax" : @(listModel.buyCount),
            @"C_Cycle" : listModel.Cycle,
            @"C_PriceDiffRang" : listModel.PriceDiffRang,
            @"GoodsGrade" : listModel.ProductGrade,
            @"Description" : listModel.GoodsAttr
        };
        [goodsArray addObject:dic];
    }
    
    NSDictionary *dic = @{
        @"GoodsList" : goodsArray
    };
    
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postJsonWithUrlString:addShopCart_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        [MBProgressHUD showSuccess:@"已加入购物车"];
        
        [TTCommonNetData handleShopCartCodeInfoWithArray:responseObject];
        
        if (self.addShopCartSuccess) {
            self.addShopCartSuccess();
        }
        
        // 通知购物车页面刷新
        [[TTLoginSingle sharedSingle].shopCartSubject sendNext:@(1)];
        
        [self dismiss];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self];
    
}

/// 立即购买
- (void)buyBtnClick
{
    if (self.selectArray.count == 0) {
        [MBProgressHUD showAutoHideMessage:@"请选择货品"];
        return;
    }
    
    [self dismiss];
    TTNewOrderDetailViewController *orderDetailVC = [[TTNewOrderDetailViewController alloc] init];
    [[LLRouteTool getCurrentNavigationController] pushViewController:orderDetailVC animated:YES];
    
}

- (void)setupSubviews
{
    UIBezierPath *bgPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer *bgLayer = [CAShapeLayer layer];
    bgLayer.path = bgPath.CGPath;
    bgLayer.fillColor = UIColor.whiteColor.CGColor;
    [self.layer addSublayer:bgLayer];
    
    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, 54)];
    [self addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self);
        make.height.mas_equalTo(54);
    }];
    
    CGFloat btnW = (bottomView.width-40-35) * 0.5;
    UIButton *addCartBtn = [UIButton createButtonWithTitle:@"加入购物车" titleColor:UIColorHex(#8B57E6) titleFontSize:14 borderColor:UIColorHex(#8B57E6) cornerRadius:20 contentEdgeInsets:UIEdgeInsetsZero target:self action:@selector(addCartBtnClick)];
    addCartBtn.isNeedLogin = YES;
    [bottomView addSubview:addCartBtn];
    [addCartBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.centerY.equalTo(bottomView);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo(btnW);
    }];
    
    UIButton *buyBtn = [UIButton createButtonWithTitle:@"立即购买" titleColor:UIColor.whiteColor titleFont:[UIFont systemFontOfSize:14] backgroundColor:UIColorHex(#8B57E6) cornerRadius:20 target:self action:@selector(buyBtnClick)];
    buyBtn.isNeedLogin = YES;
    [bottomView addSubview:buyBtn];
    [buyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(bottomView.mas_right).offset(-20);
        make.centerY.equalTo(bottomView);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo(btnW);
    }];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerView.mas_bottom);
        make.left.right.equalTo(self);
        make.bottom.equalTo(bottomView.mas_top);
    }];
    
    UIButton *closeBtn = [UIButton createButtonWithImage:[UIImage imageNamed:@"close_gray"] target:self action:@selector(dismiss)];
    closeBtn.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    [self addSubview:closeBtn];
    [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.equalTo(self);
    }];
    
}

- (void)setupFooterView
{
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, 100)];
    footView.backgroundColor = [UIColor whiteColor];
    
    UIImageView *bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"去定制背景"]];
    bgImageView.frame = CGRectMake(15, 15, footView.width - 30, 70);
    bgImageView.contentMode = UIViewContentModeScaleAspectFill;
    bgImageView.userInteractionEnabled = YES;
    bgImageView.layer.masksToBounds = YES;
    [footView addSubview:bgImageView];
    
    UILabel *infoLabel = [UILabel labelWithTitle:@"没有找到您心仪的手寸/镶口" color:UIColorHex(333333) font:[UIFont boldSystemFontOfSize:14]];
    [bgImageView addSubview:infoLabel];
    [infoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.centerY.equalTo(bgImageView);
    }];
    
    UIButton *btn = [UIButton createButtonWithTitle:@"下单定制 >" titleColor:UIColorHex(#8B57E6) titleFont:[UIFont systemFontOfSize:13] backgroundColor:nil target:self action:@selector(gotoCustomView)];
    btn.layer.cornerRadius = 13;
    btn.layer.borderColor = UIColorHex(#8B57E6).CGColor;
    btn.layer.borderWidth = 0.75;
    [bgImageView addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(bgImageView.mas_right).offset(-20);
        make.width.mas_equalTo(85);
        make.height.mas_equalTo(26);
        make.centerY.equalTo(bgImageView);
    }];
    
    self.tableView.tableFooterView = footView;
    
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 120;
        [_tableView registerClass:[TTExistGoodsTableViewCell class] forCellReuseIdentifier:@"cell"];
        _tableView.tableFooterView = [UIView new];
        [self addSubview:_tableView];
        
        
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)selectArray
{
    if (!_selectArray) {
        _selectArray = [NSMutableArray array];
    }
    return _selectArray;
}

- (TTExistGoodsChooseHeaderView *)headerView
{
    if (!_headerView) {
        _headerView = [[TTExistGoodsChooseHeaderView alloc] initWithFrame:CGRectMake(0, 0, self.width, 130)];
        [self addSubview:_headerView];
    }
    return _headerView;
}


@end
